// 防抖：触发后一定时间内没有再触发才执行
export const debounce = (func, delay = 300) => {
	let timeout;
	return function(...args) {
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			func.apply(this, args);
		}, delay);
	};
};

// 节流：在指定时间间隔内只允许一次事件执行
export const throttle = (func, delay = 300) => {
	let lastTime = 0;
	return function(...args) {
		const now = new Date().getTime();
		if (now - lastTime >= delay) {
			lastTime = now;
			func.apply(this, args);
		}
	};
};

// 深拷贝
export const deepClone = (obj) => {
	return JSON.parse(JSON.stringify(obj));
};

// 格式化时间
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
	const dt = new Date(date);
	const map = {
		'YYYY': dt.getFullYear(),
		'MM': String(dt.getMonth() + 1).padStart(2, '0'),
		'DD': String(dt.getDate()).padStart(2, '0'),
		'HH': String(dt.getHours()).padStart(2, '0'),
		'mm': String(dt.getMinutes()).padStart(2, '0'),
		'ss': String(dt.getSeconds()).padStart(2, '0')
	};
	return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => map[match]);
};

// 获取 URL 参数
export const getQueryParams = (url = window.location.href) => {
	const params = {};
	const queryString = url.split('?')[1];
	if (queryString) {
		queryString.split('&').forEach((param) => {
			const [key, value] = param.split('=');
			params[key] = decodeURIComponent(value);
		});
	}
	return params;
};

// 检查浏览器类型
export const getBrowserInfo = () => {
	const ua = navigator.userAgent;
	if (/Chrome/.test(ua) && /Google Inc/.test(navigator.vendor)) {
		return 'Chrome';
	} else if (/Safari/.test(ua) && /Apple Computer/.test(navigator.vendor)) {
		return 'Safari';
	} else if (/Firefox/.test(ua)) {
		return 'Firefox';
	} else if (/MSIE|Trident/.test(ua)) {
		return 'Internet Explorer';
	} else {
		return 'Other';
	}
};

// 判断是否为手机号
export const isValidPhoneNumber = (phone) => {
	const reg = /^1[3-9]\d{9}$/;
	return reg.test(phone);
};

// 日期时间差
export const dateDiff = (startDate, endDate) => {
	const start = new Date(startDate);
	const end = new Date(endDate);
	const diffTime = end - start;
	const days = Math.floor(diffTime / (1000 * 60 * 60 * 24));
	const hours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60));
	return {
		days,
		hours,
		minutes
	};
};

// 本地存储封装
export const setLocalStorage = (key, value) => {
	if (typeof value === 'object') {
		value = JSON.stringify(value);
	}
	localStorage.setItem(key, value);
};

export const getLocalStorage = (key) => {
	const value = localStorage.getItem(key);
	try {
		return JSON.parse(value);
	} catch (e) {
		return value;
	}
};

export const removeLocalStorage = (key) => {
	localStorage.removeItem(key);
};

// 生成 UUID
export const generateUUID = () => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
		const r = Math.floor(Math.random() * 16); 
		const v = c === 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
};


// 弹出提示框
export const showToast = (message, duration = 1500, icon = 'none') => {
	uni.showToast({
		title: message,
		duration,
		icon
	});
};

// 处理图片加载失败的默认图片
export const handleImageError = (event, defaultImage) => {
	event.target.src = defaultImage || 'path/to/default/image.png';
};

// 检查对象是否为空
export const isEmptyObject = (obj) => {
	return Object.keys(obj).length === 0 && obj.constructor === Object;
};

// URL 转码
export const encodeUrl = (url) => {
	return encodeURIComponent(url);
};

export const decodeUrl = (url) => {
	return decodeURIComponent(url);
};

// 图片大小限制
export const validateImageSize = (file, maxSize = 5 * 1024 * 1024) => { 
	if (file.size > maxSize) {
		return false;
	}
	return true;
};

// 手机号加密显示
export const encryptPhone = (phone) => {
	return phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
};

// 扫描二维码
export const scanCode = () => {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			success: (res) => {
				if (res.result) {
					resolve(res.result);
				} else {
					reject('扫码结果为空');
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};